import 'dart:io';

import 'package:cgvc/data/article_http.dart';
import 'package:cgvc/dialog/author_dialog.dart';
import 'package:cgvc/helper/provider_helper.dart';
import 'package:cgvc/helper/string_helper.dart';
import 'package:cgvc/page/article_item_widget.dart';
import 'package:cgvc/util/resource_util.dart';
import 'package:cgvc/util/toast_util.dart';
import 'package:cgvc/view_model/theme_view_model.dart';
import 'package:cgvc/widget/animated_switcher_icon_widget.dart';
import 'package:cgvc/widget/tab_bar_widget.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key key}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage>
    with SingleTickerProviderStateMixin {
  DateTime _lastPressedAt;
  var _listTab = ["热门话题", "科技动态", "开发者资讯", "区块链"];
  var _listUrls = [
    ArticleHttp.API_TOPIC,
    ArticleHttp.API_NEWS,
    ArticleHttp.API_TECH_NEWS,
    ArticleHttp.API_BLOCK_CHAIN,
  ];
  TabController _tabController;
  ValueChanged<int> _onTabTap;

  @override
  void initState() {
    super.initState();
    _tabController =
        TabController(initialIndex: 0, length: _listTab.length, vsync: this);

    _onTabTap = (index) {
      LogUtil.v('TabController:$index');
    };
  }

  //深色浅色模式切换
  void switchDarkMode(BuildContext context) {
    //如果设备是深色模式，就不让切换
    if (ThemeViewModel.platformDarkMode) {
      ToastUtil.show(StringHelper.getS().tipSwitchThemeWhenPlatformDark);
    } else {
      ProviderHelper.of<ThemeViewModel>(context).switchTheme(
          userDarkMode: Theme.of(context).brightness == Brightness.light);
    }
  }

  @override
  void didUpdateWidget(covariant HomePage oldWidget) {
    super.didUpdateWidget(oldWidget);

    LogUtil.v('home_page_didUpdateWidget');
  }

  @override
  Widget build(BuildContext context) {
    //返回控制键
    return WillPopScope(
      onWillPop: () async {
        //1.5秒内按两次返回就退出应用
        if (_lastPressedAt == null ||
            DateTime.now().difference(_lastPressedAt) >
                Duration(milliseconds: 1500)) {
          //两次点击时间间隔超过阈值重新计时
          _lastPressedAt = DateTime.now();
          ToastUtil.show(StringHelper.getS().quitApp,
              position: ToastPosition.bottom,
              duration: Duration(milliseconds: 1500));
          return false;
        }
        exit(0);
        return true;
      },
      child: Scaffold(
        backgroundColor: Theme.of(context).cardColor,
        appBar: PreferredSize(
          //appbar的高度
          preferredSize: Size.fromHeight(40),
          child: AppBar(
            title: Image.asset(
              'assets/images/title.png',
              width: 108,
              color: Theme.of(context).appBarTheme.iconTheme.color,
              fit: BoxFit.fill,
              filterQuality: FilterQuality.high,
              colorBlendMode: BlendMode.srcIn,
            ),
            actions: <Widget>[
              //更多信息
              AnimatedSwitcherIconWidget(
                defaultIcon: Icons.info,
                swithchIcon: Icons.info_outline,
                tooltip: StringHelper.getS().moreSetting,
                onPressed: () => showAuthorDialog(context),
                checkTheme: true,
              ),

              //暗黑模式切换
              AnimatedSwitcherIconWidget(
                defaultIcon: Icons.brightness_2,
                swithchIcon: Icons.brightness_5,
                tooltip: ThemeViewModel.darkMode
                    ? StringHelper.getS().darkMode
                    : StringHelper.getS().lightMode,
                onPressed: () => switchDarkMode(context),
              )
            ],
          ),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            //tab
            Container(
              height: 36,
              width: double.infinity,
              color: Theme.of(context).appBarTheme.color,
              child: TabBarWidget(
                tabController: _tabController,
                labels: _listTab,
                onTap: _onTabTap,
              ),
            ),

            //分割线
            Container(
              width: double.infinity,
              decoration: BoxDecoration(
                border: Decorations.lineBoxBorder(
                  context,
                  bottom: true,
                ),
              ),
            ),

            //内容
            Expanded(
              flex: 1,
              child: TabBarView(
                controller: _tabController,
                children: List.generate(
                    _listTab.length,
                    (index) => ArticleItemWidget(
                          url: _listUrls[index],
                        )),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
